package com.endlessblue.visa.util;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Component;


/**
 * String session缓存工具类
 * @author sonta
 *
 */
@Component
public class CacheUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(CacheUtil.class);
	
	private static EhCacheCacheManager cacheManager;
	
	/**
	 * 获取缓存
	 * @param cacheName
	 * @param key
	 * @return
	 */
	public static Object getCache(String cacheName, String key) {  
		Cache cache = cacheManager.getCache(cacheName);
		if (cache == null) {
			logger.error("cache - {} is null", cacheName);
			return null;
		}
		ValueWrapper value = cache.get(key);
		if (value == null) {
			return null;
		}
		return value.get();
	}  
	/**
	 * 添加缓存  
	 * @param cacheName
	 * @param key
	 * @param value
	 */
	public static void setCache(String cacheName, Object key, Object value){  
		Cache cache = cacheManager.getCache(cacheName);
		if (cache == null) {
			logger.error("cache - {} is null", cacheName);
			return;
		}
		cache.put(key, value);
	}
	
	public static void clearCache(String cacheName, Object key) {
		Cache cache = cacheManager.getCache(cacheName);
		if (cache == null) {
			logger.error("cache - {} is null", cacheName);
			return;
		}
		cache.evict(key);
	}
	
	@Resource
	public void setCacheManager(EhCacheCacheManager cacheManager) {
		CacheUtil.cacheManager = cacheManager;
	}
	
}
